﻿using HttpClientHelper;
using KinTN_WMS_CL.Extensions;
using KinTN_WMS_CL.Model;
using Prism.Events;
using Prism.Mvvm;
using Prism.Navigation;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Markup;

namespace KinTN_WMS_CL.UserControlModels
{
    public class InterfaceViewModel : BindableBase, INavigationAware
    {
        private readonly IEventAggregator _eventAggregator;
        private int _pageIndex = 1;
        private int _totalCount = 1;
        private int _pageSize = 10; // 默认每页显示 10 项

        private readonly IHttpClients _httpClients;

        public int PageIndex
        {
            get => _pageIndex;
            set
            {
                if (SetProperty(ref _pageIndex, value))
                {
                    // 当 PageIndex 变化时，重新加载数据
                    LoadData();
                }
            }
        }

        public int TotalCount
        {
            get => _totalCount;
            set => SetProperty(ref _totalCount, value);
        }

        public int PageSize
        {
            get => _pageSize;
            set => SetProperty(ref _pageSize, value);
        }

        public List<RequestLogModel> _data;

        public List<RequestLogModel> Data
        {
            get => _data;
            set => SetProperty(ref _data, value);
        }
        public InterfaceViewModel(IHttpClients httpClients, IEventAggregator eventAggregator)
        {
            _httpClients = httpClients;
            _eventAggregator = eventAggregator;
            LoadData();
        }

        private async void LoadData()
        {
            try
            {
                List<RequestLogModel> inDataModels = new List<RequestLogModel>();
                // 设置默认的内容
                Data = inDataModels;
                await Task.Run(async () =>
                 {
                     var list = await _httpClients.GetAsync<ResponseModel<List<RequestLogModel>>>($"http://localhost:5032/api/Log/list?pageNumber={PageIndex}", null);
                     // Set up pagination
                     Data = list.Data;
                     TotalCount = (int)Math.Ceiling((list.total / 20.0));
                 });

            }
            catch (Exception)
            {
                _eventAggregator.GetEvent<NotificationEvent>().Publish(new Message()
                {
                    info = "请检查网络连接，稍后重试！",
                    type = MessageEnum.Error,
                });
            }
        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            LoadData();
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return false;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {

        }
    }
}
